import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import store from '@/store'
import type { StateAll } from '@/store'
import _ from 'loadsh'

const LoginView = () => import('@/views/Login/index.vue');
const SingView = () => import('@/views/Sign/index.vue');
const HomeView = () => import('@/views/Home/index.vue');
const ExceptionView = () => import('@/views/Exception/index.vue');
const CheckView = () => import('@/views/Check/index.vue');
const ApplyView = () => import('@/views/Apply/index.vue');
const NotAuth = () => import('@/views/NotAuth/index.vue');
const NotFound = () => import('@/views/NotFound/index.vue');
const NotServer = () => import('@/views/NotServer/index.vue');

declare module 'vue-router' {
  interface RouteMeta{
    menu?: boolean,
    title?: string,
    icon?: string,
    auth?: boolean
  }
}

const routes: Array<RouteRecordRaw> = [
  { 
    path: '/',
    name: 'home',
    component: HomeView,
    redirect: '/sign',
    meta: {
      menu: true,
      title: '考勤管理',
      icon: 'document-copy',
      auth: true
    },
    children: [
      {
        path: 'sign',
        name: 'sign',
        component: SingView,
        meta: {
          menu: true,
          title: '在线打卡签到',
          icon: 'calendar',
          auth: true
        },
        async beforeEnter (_to, _from, next) {
          const id = (store.state as StateAll).users.infos._id
          const signInfos = (store.state as StateAll).signs.infos
          const newsInfos = (store.state as StateAll).news.info
          if (_.isEmpty(signInfos)) {
            const res = await store.dispatch('signs/getTime', { userid: id })
            if (res.data.errcode === 0) {
              store.commit('signs/updateInfos', res.data.infos)
            } else {
              return
            }
          }
          if (_.isEmpty(newsInfos)) {
            const res = await store.dispatch('news/getRemind', { userid: id })
            if (res.data.errcode === 0) {
              store.commit('news/updateInfo', res.data.info)
            } else {
              return
            }
          }
          next()
        }
      },
      {
        path: 'check',
        name: 'check',
        component: CheckView,
        meta: {
          menu: true,
          title: '我的考勤审批',
          icon: 'finished',
          auth: true,
        },
        async beforeEnter(_to, _from, next) {
          const id = (store.state as StateAll).users.infos._id
          const checkList = (store.state as StateAll).checks.checkList
          const newsInfo = (store.state as StateAll).news.info
          if (_.isEmpty(checkList)) {
            const res = await store.dispatch('checks/getApply', { approverid: id })
            if (res.data.errcode === 0) {
              store.commit('checks/updateCheckList', res.data.rets)
            } else {
              return
            }
          }
          if (newsInfo.approver) {
            const res = await store.dispatch('news/putRemind', { userid: id, approver: false })
            if (res.data.errcode === 0) {
              store.commit('news/updateInfo', res.data.info)
            } else {
              return
            }
          }
          next()
        }
      },
      {
        path: 'apply',
        name: 'apply',
        component: ApplyView,
        meta: {
          menu: true,
          title: '添加考勤审批',
          icon: 'document-add',
          auth: true,
        },
        async beforeEnter(_to, _from, next) {
          const id = (store.state as StateAll).users.infos._id
          const applyList = (store.state as StateAll).checks.applyList
          const newsInfo = (store.state as StateAll).news.info
          if (_.isEmpty(applyList)) {
            const res = await store.dispatch('checks/getApply', { aplicantid: id })
            if (res.data.errcode === 0) {
              store.commit('checks/updateApplyList', res.data.rets)
            } else {
              return
            }
          }
          if (newsInfo.applicant) {
            const res = await store.dispatch('news/putRemind', { userid: id, applicant: false })
            if (res.data.errcode === 0) {
              store.commit('news/updateInfo', res.data.info)
            } else {
              return
            }
          }
          next()
        }
      },
      {
        path: 'exception',
        name: 'exception',
        component: ExceptionView,
        meta: {
          menu: true,
          title: '异常考勤查询',
          icon: 'warning',
          auth: true,
        },
        async beforeEnter (_to, _from, next) {
          const id = (store.state as StateAll).users.infos._id
          const signInfos = (store.state as StateAll).signs.infos
          const applyList = (store.state as StateAll).checks.applyList
          const newsInfos = (store.state as StateAll).news.info
          if (_.isEmpty(signInfos)) {
            const res = await store.dispatch('signs/getTime', { userid: id })
            if (res.data.errcode === 0) {
              store.commit('signs/updateInfos', res.data.infos)
            } else {
              return
            }
          }
          if (_.isEmpty(applyList)) {
            const res = await store.dispatch('checks/getApply', { aplicantid: id })
            if (res.data.errcode === 0) {
              store.commit('checks/updateApplyList', res.data.rets)
            } else {
              return
            }
          }
          if (_.isEmpty(newsInfos)) {
            const res = await store.dispatch('news/getRemind', { userid: id })
            if (res.data.errcode === 0) {
              store.commit('news/updateInfo', res.data.info)
            } else {
              return
            }
          }
          next()
        }
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
  },
  {
    path: '/403',
    name: 'notAuth',
    component: NotAuth
  },
  {
    path: '/404',
    name: 'notFound',
    component: NotFound
  },
  {
    path: '/500',
    name: 'notServer',
    component: NotServer
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, _from, next) => {
  const token = (store.state as StateAll).users.token
  const infos = (store.state as StateAll).users.infos
  if (to.meta.auth && _.isEmpty(infos)) {
    if (token) {
      store.dispatch('users/infos').then((res) => {
        if(res.data.errcode === 0){
          store.commit('users/updateInfos', res.data.infos)
          if(res.data.infos.permission.includes(to.name)){
            next()
          }
          else{
            next('/403')
          }
        }
      })
    } else {
      next('/login')
    }
  } else {
    // 已登录不再返回登录页
    if (token && to.path === '/login') {
      next('/')
    } else {
      next()
    }
  }
})

export default router
